package com.tanjor.main.sys.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tanjor.common.datatable.PageReq;
import com.tanjor.common.datatable.PageResp;
import com.tanjor.sys.dubbo.dto.SysRoleDTO;
import com.tanjor.sys.dubbo.impl.interfaces.ISysMenuDubbo;
import com.tanjor.sys.dubbo.impl.interfaces.ISysRoleDubbo;

@Controller
@RequestMapping("/sys/role")
public class RoleController {
	
	@Resource
	private ISysRoleDubbo sysRoleDubbo;
	
	@Resource
	private ISysMenuDubbo sysMenuDubbo;
	
	@RequestMapping("/list")
	public String list(Model model){
		return "manage/sys/role-list";
	}
	
	@RequestMapping("/loadPage")
	@ResponseBody
	public PageResp loadPage(PageReq pageReq){
		PageResp page = sysRoleDubbo.findPage(pageReq);
		return page;
	}
	
	@RequestMapping("/goEdit/{id}")
	public String eidt(Model model,@PathVariable String id){
		model.addAttribute("id", id);
		return "manage/sys/role-edit";
	}
	
	@RequestMapping("/goAdd")
	public String add(){
		return "manage/sys/role-edit";
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public Map<String,Object> save(SysRoleDTO role){
		if(StringUtils.isNotBlank(role.getId())){
			return sysRoleDubbo.update(role);
		}else{
			return sysRoleDubbo.insert(role);
		}
	}
	
	@RequestMapping("/rolemenu/{code}")
	public String roleMenus(Model model,@PathVariable String code){
		model.addAttribute("code", code);
		return "/manage/sys/role-menu";
	}
		
	@RequestMapping("/saveRoleMenu")
	@ResponseBody
	public Map<String,Object> saveRoleMenu(String roleCode,String menuIds){
		return sysMenuDubbo.saveRoleMenus(roleCode, menuIds);
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public Map<String,Object> del(SysRoleDTO role){		
		 try{
			 return sysRoleDubbo.deleteById(role.getId());
		 }catch (Exception e) {
			 Map<String,Object> result = new HashMap<String, Object>();
			// TODO: handle exception
			 result.put("result", false);
			 result.put("msg", "删除失败！");
			 return result;		
		 }	
	}
	
	@RequestMapping("/getModel")
	@ResponseBody
	public SysRoleDTO getModel(String id){
		if(StringUtils.isNotBlank(id)){
			SysRoleDTO role = sysRoleDubbo.findById(id);
			return role;
		}else{
			return new SysRoleDTO();
		}
	}
	
	@RequestMapping("/loadTreeRole")
	@ResponseBody
	public List<Map<String,Object>> loadTreeRole(String userId){
		return sysRoleDubbo.findTreeByUser(userId);
	}
}
